import 'package:flutter/material.dart';
import 'package:get/get.dart';



// app路由监听
class AppRoutesObserver extends RouteObserver {

  static AppRoutesObserver get observer =>_observer;
  static final AppRoutesObserver _observer =  AppRoutesObserver._();
  final List<Route> _appRoutes = [];


  AppRoutesObserver._();

  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    _appRoutes.insert(0, route);
  }

  @override
  void didPop(Route route, Route? previousRoute) {
    super.didPop(route, previousRoute);
    _appRoutes.remove(route);
  }


  bool isPageInStack(String name ){
    var first =  _appRoutes.where((e)=> e.settings.name == name).firstOrNull;
    return first != null;
  }

  // 移除指定路由页面
  Future removeRoute<S extends GetxController>(String routeName) async {
    // 如果弹出的不是广告占位页面则移除
    for (Route route in _appRoutes) {
      if (route.settings.name == null) {
        continue;
      }
      Uri? url = Uri.tryParse(route.settings.name!);
      if (url != null && url.path == routeName) {
        _appRoutes.remove(route);
        // 从路由栈中移除
        Get.removeRoute(route);
        // 移除controller
        await Get.delete<S>(force: true);
        break;
      }
    }
  }
}